package validators

import (
	"regexp"
	"sync"

	"apedge/pkg/loggers"

	"github.com/go-playground/validator/v10"
)

var once sync.Once
var instance *validator.Validate
var logger = loggers.LogInstance()

func ValidatorInstance() *validator.Validate {
	once.Do(func() {
		instance = validator.New()
	})
	return instance
}

func InitValidator() {
	validWorker := ValidatorInstance()
	err := validWorker.RegisterValidation("name-checker",
		func(fl validator.FieldLevel) bool {
			inputName := fl.Field().String()
			r, _ := regexp.Compile("^[\u4e00-\u9fa5_a-zA-Z0-9-.]{2,20}$") // 中文、英文字母、数字、下划线、中横线
			return r.Match([]byte(inputName))
		})
	if err != nil {
		logger.Panicln("validator init fail:", err)
	}
}
